#!/bin/sh
#
# Starts atguigu-gateway
#

start() {
	# delete old logfile
	rm -rf /var/log/atguigu-gateway.log

	# create link
	if [ ! -f "/usr/bin/atguigu-gateway" ]; then
		ln -s "/usr/bin/atguigu-gateway.active" "/usr/bin/atguigu-gateway"
	fi

	if [ -f "/tmp/atguigu-gateway.update" ]; then
		# reboot because of update
		chmod 755 "/tmp/atguigu-gateway.update" &&
			mv -f "/usr/bin/atguigu-gateway.active" "/usr/bin/atguigu-gateway.old" &&
			mv -f "/tmp/atguigu-gateway.update" "/usr/bin/atguigu-gateway.active"
	elif [ -f "/tmp/atguigu-gateway.error" ]; then
		# reboot because of errors
		rm -f "/tmp/atguigu-gateway.error"
		if [ -f "/usr/bin/atguigu-gateway.old" ]; then
			mv -f "/usr/bin/atguigu-gateway.old" "/usr/bin/atguigu-gateway.active"
		fi
	fi

	echo 1000 >/proc/sys/fs/mqueue/msg_max

	printf "Starting atguigu-gateway: "

	start-stop-daemon -S -q --exec /usr/bin/atguigu-gateway -- daemon
	result=$?
	[ $result = 0 ] && echo "OK" || echo "FAIL"
}
stop() {
	printf "Stopping atguigu-gateway: "
	start-stop-daemon -K -q -x /usr/bin/atguigu-gateway daemon
	result=$?
	[ $result = 0 ] && echo "OK" || echo "FAIL"
}
restart() {
	stop
	start
}

case "$1" in
start)
	start
	;;
stop)
	stop
	;;
restart | reload)
	restart
	;;
*)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
	;;
esac

exit $result
